<template>
  <div class="container">
    <el-card>
      <el-breadcrumb
        v-if="!$route.query.name == ''"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ $route.query.name }}</el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        <el-divider></el-divider>
      </el-breadcrumb>
      <el-row :gutter="5">
        <el-form :model="searchForm" ref="searchFormRef">
          <el-col :span="6">
            <el-form-item label="目录" label-width="60px" prop="tagName">
              <el-input v-model="searchForm.tagName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" label-width="60px" prop="state">
              <el-select v-model="searchForm.state" placeholder="请选择">
                <el-option
                  v-for="item in statusOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6"
            ><el-button @click="clearForm">清除</el-button>
            <el-button type="primary" @click="searchTags">搜索</el-button>
          </el-col>
          <el-col :span="6">
             <div class="btn">
            <el-button
              type="text"
              v-show="!$route.query.name == ''"
              @click="$router.back()"
              >←返回学科</el-button
            >
            <el-button type="success" icon="el-icon-edit" @click="addTags"
              >新增目录</el-button
            >
            </div>
          </el-col>
        </el-form>
      </el-row>
      <el-alert
        :title="'数据一共' + total + '条'"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 表格区域 -->
      <el-table :data="tagsList">
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="所属学科" prop="subjectName"></el-table-column>
        <el-table-column label="标签名称" prop="tagName"></el-table-column>
        <el-table-column label="创建者" prop="username"></el-table-column>
        <el-table-column label="创建日期">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            {{ scope.row.state === 1 ? "已启用" : "已禁用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="changeState(scope.row)">{{
              scope.row.state === 1 ? "禁用" : "启用"
            }}</el-button>
            <el-button
              type="text"
              :disabled="scope.row.state === 1"
              @click="editTags(scope.row)"
              >修改</el-button
            >
            <el-button
              type="text"
              :disabled="scope.row.state === 1"
              @click="deleteTags(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="searchForm.pagesize"
        layout="sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 新增标签对话框 -->
    <el-dialog
      title="新增目录"
      :visible.sync="dialogVisible"
      width="30%"
      @closed="onClosedAdd"
    >
      <el-form :model="addForm" :rules="addRules" ref="addFormRef">
        <el-form-item
          label="所属学科"
          label-width="80px"
          prop="subjectID"
          v-if="$route.query.id == null"
        >
          <el-select
            v-model="addForm.subjectID"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in subjectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" label-width="80px" prop="tagName">
          <el-input v-model="addForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onAddTags">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改标签内容对话框 -->
    <el-dialog
      title="修改标签"
      :visible.sync="editDialogVisible"
      width="30%"
      @closed="onCloseEdit"
    >
      <el-form :model="editForm" :rules="addRules" ref="editFormRef">
        <el-form-item
          label="所属学科"
          label-width="80px"
          prop="subjectID"
          v-if="$route.query.id == null"
        >
          <el-select
            v-model="editForm.subjectID"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in subjectOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" label-width="80px" prop="tagName">
          <el-input v-model="editForm.tagName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onEditTags">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, changeState, update, remove } from "@/api/hmmm/tags";
import { status } from "@/api/hmmm/constants";
import { simple } from "@/api/hmmm/subjects";
export default {
  name: "tags",
  data() {
    return {
      tagsList: [],
      searchForm: {
        page: 1,
        pagesize: 10,
        subjectID: null,
        tagName: "",
        state: null,
      },
      total: 0,
      statusOption: status, //状态
      dialogVisible: false, //新增目录对话框显示与隐藏
      addForm: {
        subjectID: "", //学科id
        tagName: "", //标签名称
      },
      subjectOption: [],
      addRules: {
        subjectID: [
          { required: true, message: "请选择所属学科", trigger: "change" },
        ],
        tagName: [
          { required: true, message: "请输入标签名称", trigger: "blur" },
        ],
      }, //新增标签验证规则
      editDialogVisible: false, //修改标签对话框显示与隐藏
      editForm: {
        subjectID: "",
        tagName: "",
        id: "",
      },
    };
  },
  methods: {
    //请求标签列表
    async getTagsList() {
      try {
        if (this.$route.query.id)
          this.searchForm.subjectID = this.$route.query.id;
        else this.searchForm.subjectID = null;
        const { data: res } = await list(this.searchForm);
        this.tagsList = res.items;
        this.total = res.counts;
        // console.log(res);
      } catch (error) {
        this.$message.error("请求标签列表数据失败");
      }
    },
    //清空搜索框
    clearForm() {
      this.$refs.searchFormRef.resetFields();
      this.searchForm.page = 1;
      this.getTagsList();
    },
    //搜索标签
    async searchTags() {
      this.searchForm.page = 1;
      this.getTagsList();
    },
    //页尺寸发生变化
    handleSizeChange(val) {
      this.searchForm.pagesize = val;
      this.getTagsList();
    },
    //翻页
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.getTagsList();
    },

    //修改标签状态
    async changeState(tag) {
      try {
        await changeState({ id: tag.id, state: tag.state === 1 ? 0 : 1 });
        this.getTagsList();
      } catch (error) {
        this.$message.error("修改标签状态失败");
      }
    },
    //新增标签
    async addTags() {
      try {
        const { data: res } = await simple();
        this.subjectOption = res;
      } catch (error) {
        this.$message.error("获取学科列表失败");
      }
      if (this.$route.query.id) this.addForm.subjectID = this.$route.query.id;
      this.dialogVisible = true;
    },
    //发起新增标签请求
    async onAddTags() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          try {
            await add(this.addForm);
            this.$message.success("新增标签成功");
            this.getTagsList();
            this.dialogVisible = false;
          } catch (error) {
            console.log(error);
          }
        }
      });
    },
    //关闭对话框
    onClosedAdd() {
      this.$refs.addFormRef.resetFields();
      this.addForm.subjectID = "";
    },
    //修改标签内容
    async editTags(tag) {
      this.editForm.id = tag.id;
      try {
        const { data: res } = await simple();
        this.subjectOption = res;
        if (this.$route.query.id)
          this.editForm.subjectID = this.$route.query.id;
      } catch (error) {
        this.$message.error("获取学科列表失败");
      }
      this.editForm.subjectID = tag.subjectID;
      this.editForm.tagName = tag.tagName;
      this.editDialogVisible = true;
    },
    //发起修改标签请求
    async onEditTags() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          try {
            await update(this.editForm);
            this.getTagsList();
            this.$message.success("修改标签成功");
            this.editDialogVisible = false;
          } catch (error) {
            this.$message.error("修改标签失败");
          }
        }
      });
    },
    //关闭修改标签对话框
    onCloseEdit() {
      //重置表单数据
      this.$refs.editFormRef.resetFields();
      this.editForm.subjectID = "";
      this.editForm.id = "";
    },
    //删除标签
    deleteTags(tag) {
      this.$confirm("此操作将永久删除该标签, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await remove({ id: tag.id });
            this.$message.success("删除成功");
            const totalpage = Math.ceil(
              (this.total - 1) / this.searchForm.pagesize
            );
            this.searchForm.page =
              this.searchForm.page > totalpage
                ? totalpage
                : this.searchForm.page;
            this.searchForm.page =
              this.searchForm.page < 1 ? 1 : this.searchForm.page;
            this.getTagsList();
          } catch (error) {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
  created() {
    this.getTagsList();
  },
  updated() {
    // this.addForm.subjectID = "";
  },
};
</script>

<style scoped lang='less'>
.btn {
  float: right;
}
.el-breadcrumb {
  margin-bottom: 0;
}
.el-pagination{
  display: flex;
  justify-content: flex-end;
}
</style>
